package com.cheyunkeji.er.http;

import android.text.TextUtils;
import android.util.Log;

import com.cheyun.netsalev3.MyApplication;
//import com.cheyun.netsalev3.utils.LogInterceptor;
import com.cheyun.netsalev3.utils.MySharedPreferences;
import com.cheyunkeji.er.app.UserInfoManager;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.builder.HasParamsable;
import com.zhy.http.okhttp.builder.OkHttpRequestBuilder;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * API 调用工具类
 */
public class ApiClient {

    // init
    static {
//        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        // custom client
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                // 读写请求超时
                .connectTimeout(HttpConstants.CONN_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(HttpConstants.READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(HttpConstants.WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
//                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                // 失败不重试
//                .retryOnConnectionFailure(false)
                .build();

        OkHttpUtils.initClient(httpClient);

        //http log调试开关
//        OkHttpUtils.getInstance().debug("HTTP", true);
    }

    // 设置请求参数
    private static void setParams(OkHttpRequestBuilder builder, Map<String, String> params) {
        // 添加 cookies

//        if (!TextUtils.isEmpty(Settings.Global.getCookie())) {
//            builder.addHeader("cookie", Global.getCookie());
//        }
        if (params == null || params.isEmpty()) {
            params = new HashMap<>();
        }
        // 添加参数对
        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getY7e_ckey())) {
            params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
            params.put("Y7e_ckey", UserInfoManager.getInstance(MyApplication.getInstance()).getY7e_ckey());
        }
        params.put("cauthkey", MySharedPreferences.INSTANCE.getCauthkey());
        params.put("app_version", MyApplication.getInstance().getApp_version());
        Log.e("LogInterceptor", "RequestParams===== " + new Gson().toJson(params));
        if (builder instanceof HasParamsable) {
            ((HasParamsable) builder).params(params);

        }


        // user-agent
//        builder.addHeader("User-Agent", HttpConstants.USER_AGENT);
    }

    /**
     * Http GET 同步请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 响应内容
     * @throws IOException
     */
    public static Response get(String url, Map<String, String> params) throws IOException {
        GetBuilder builder = OkHttpUtils.get()
                .url(url);
        setParams(builder, params);
        return builder.tag(url).build().execute();
    }

    /**
     * Http GET 异步请求
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callback 响应回调
     */
    public static void get(String url, Map<String, String> params, Callback callback) {
        GetBuilder builder = OkHttpUtils.get()
                .url(url);
        setParams(builder, params);
        builder.tag(url).build().execute(callback);
    }


    /**
     * Http GET 异步请求(无参数)
     *
     * @param url      请求地址
     * @param callback 响应回调
     */
    public static void get(String url, Callback callback) {
        get(url, null, callback);
    }

    /**
     * Http POST 参数异步请求
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callback 响应回调
     */
    public static void postForm(String url, HashMap<String, String> params, Callback callback) {
        PostFormBuilder builder = OkHttpUtils.post()
                .url(url);
        setParams(builder, params);
        builder.tag(url).build().execute(callback);
    }

    /**
     * Http POST 无参数异步请求
     *
     * @param url      请求地址
     * @param callback 响应回调
     */
    public static void postForm(String url, Callback callback) {
        postForm(url, null, callback);
    }

    /**
     * 上传文件 异步
     *
     * @param url      请求地址
     * @param file     上传文件
     * @param params   请求参数
     * @param callBack 响应回调
     */
    public static void postFile(String url, File file, HashMap<String, String> params, Callback callBack) {
        OkHttpRequestBuilder builder = OkHttpUtils.postFile()
                .url(url)
                .file(file);
        setParams(builder, params);
        builder.tag(url).build().execute(callBack);
    }

    /**
     * 表单形式异步上传文件
     *
     * @param url      请求地址
     * @param file     上传文件
     * @param name     表单中的name
     * @param fileName 文件名
     * @param params   请求参数
     * @param callback 响应回调
     */
    public static void postFormFile(String url, File file, String name, String fileName, HashMap<String, String> params, Callback callback) {
        PostFormBuilder builder = OkHttpUtils.post()
                .url(url)
                .addFile(name, fileName, file);
        setParams(builder, params);
        builder.tag(url).build().execute(callback);
    }


//    /**
//     * Http POST 参数异步请求
//     * post字节数组
//     *
//     * @param url      请求地址
//     * @param tag      请求标记
//     * @param params   请求参数
//     * @param callback 响应回调  Callback
//     */
//    public static void postByteArray(String url, String tag, HashMap<String, String> params, String key, String fileName, byte[] content, Callback callback) {
//        PostBytesFormBuilder postBytesFormBuilder = new PostBytesFormBuilder();
//        OkHttpRequestBuilder builder = postBytesFormBuilder
//                .addByteArray(key, fileName, content)
//                .url(url)
//                .tag(tag);
//        setParams(builder, params);
//        builder.build()
//                .connTimeOut(100000L)
//                .readTimeOut(100000L)
//                .writeTimeOut(100000L)
//                .execute(callback);
//    }


    /**
     * 取消请求
     *
     * @param tag 这个请求的url
     */
    public static void cancel(String tag) {
        if (TextUtils.isEmpty(tag)) return;
        OkHttpUtils.getInstance().cancelTag(tag);
    }
}
